package com.sc.ktapplication.common.net

import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.sc.ktapplication.MyApp
import com.sc.ktapplication.common.constant.RouteURL
import com.sc.ktapplication.common.net.entity.HttpResponseReceive
import com.sc.ktapplication.common.net.entity.HttpResponseTemp
import com.sc.ktapplication.common.util.LogUtil
import com.sc.ktapplication.common.util.RsaUtils.AESECBEncryptUtils
import okhttp3.*
import okio.Buffer
import java.io.IOException
import java.util.*

class HttpInterceptor : Interceptor {

    private val mHeaderParamsMap = HashMap<String, String>()

    private val mediaType = MediaType.parse("application/json; charset=utf-8")

    private val ticketId: String
        get() {
            val appUser = MyApp.instance.getUser()
            return appUser?.ticketId ?: ""
        }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request() // 添加新的参数，添加到url 中
        val httpUrl = oldRequest.url().newBuilder()
            .addQueryParameter("mobileFlag", "1")
            .addQueryParameter("ticketId", ticketId)

        val modifiedUrl = httpUrl.build()
        val url = modifiedUrl.url().toString()

        if (!url.contains("Encrypt")) {
            val requestBuilder = oldRequest.newBuilder().url(url)
            val request = requestBuilder.build()
            val response = chain.proceed(request)
            checkTimeout(response)
            return response
        }

        // 新的请求
        val requestBuilder = oldRequest.newBuilder().url(url)
        if (null != oldRequest.body() && oldRequest.body()!!.contentLength() > 0) {
            val buffer = Buffer()
            oldRequest.body()!!.writeTo(buffer)
            val body = buffer.readUtf8()
            LogUtil.print("httpRequest", body)
            val encryptBody = RequestBody.create(mediaType, AESECBEncryptUtils.encrypt2hex(body))
            requestBuilder.method(oldRequest.method(), encryptBody)
        }
        //添加公共参数,添加到header中
        if (mHeaderParamsMap.size > 0) {
            for ((key, value) in mHeaderParamsMap) {
                requestBuilder.header(key, value)
            }
        }

        val newRequest = requestBuilder.build()
        val response = chain.proceed(newRequest)
        val responseBody = response.peekBody(java.lang.Long.MAX_VALUE)
        val ret = responseBody.string()
        val r = JSONObject.parseObject(ret, HttpResponseReceive::class.java)

        val temp = HttpResponseTemp()
        temp.isSuccess = r.isSuccess
        temp.code = r.code
        temp.msg = r.msg

        if (r.statusCode == 1002) {//登录超时
            //ARouter.getInstance().build(RouteURL.LOGIN).navigation();
        }

        if (!TextUtils.isEmpty(r.dataStr)) {
            temp.data = decryptArray(r.dataStr!!)
            temp.dataStr = null
        }
        if (!TextUtils.isEmpty(r.obj)) {
            temp.obj = decrypt(r.obj!!)
        }
        return response.newBuilder().body(ResponseBody.create(mediaType, JSON.toJSONString(temp)))
            .build()
    }

    @Throws(IOException::class)
    private fun checkTimeout(response: Response): HttpResponseReceive {
        val responseBody = response.peekBody(java.lang.Long.MAX_VALUE)
        val ret = responseBody.string()
        val r = JSONObject.parseObject(ret, HttpResponseReceive::class.java)
        if (r.statusCode == 1002) {//登录超时
             ARouter.getInstance().build(RouteURL.LOGIN).navigation()
        }
        return r
    }

    private fun decrypt(src: String): JSONObject {
        var src = src
        if (!src.startsWith("{")) {//密文
            src = AESECBEncryptUtils.decrypt(src)
        }
        return JSON.parseObject(src)
    }

    private fun decryptArray(src: String): JSONArray {
        var src = src
        if (!src.startsWith("{")) {//密文
            src = src.replace("\"".toRegex(), "")
            src = AESECBEncryptUtils.decrypt(src)
        }
        LogUtil.print("httpResponse", src)
        return JSON.parseArray(src)
    }

    class Builder {
         private val mHttpInterceptor: HttpInterceptor = HttpInterceptor()

        private fun addHeaderParams(key: String, value: String): Builder {
            mHttpInterceptor.mHeaderParamsMap[key] = value
            return this
        }

        private fun addHeaderParams(key: String, value: Int): Builder {
            return addHeaderParams(key, value.toString())
        }

        private fun addHeaderParams(key: String, value: Float): Builder {
            return addHeaderParams(key, value.toString())
        }

        private fun addHeaderParams(key: String, value: Long): Builder {
            return addHeaderParams(key, value.toString())
        }

        private fun addHeaderParams(key: String, value: Double): Builder {
            return addHeaderParams(key, value.toString())
        }

        fun build(): HttpInterceptor {
            return mHttpInterceptor
        }
    }
}
